module ad8320ctrl
		(clock, resetn, start_adc, idle_adc, CSn, DCLK, DIN, VOUT);
input			clock, resetn;
input			start_adc;
output			idle_adc;

output			CSn, DCLK;
input			DIN;
output	[15:0]	VOUT;

reg				CSn, DCLK;
reg				idle_adc;
reg				sclr_sftreg;
reg				cnten_adcnt, sclr_adcnt;

wire			clk8;
wire			start;
wire			done_adcnt;
wire	[4:0]	ADCNT, ADCNT_REF;

assign			ADCNT_REF = 22;

parameter		IDLE=0, INIT=1, CLKLOW=2, CLKHIGH=3;
reg		[1:0]	STATE;

clk8gen			clk8gen_inst (.clock(clock), .resetn(resetn), .clk8(clk8));
mv24clk			startgen (.clock(clock), .resetn(resetn), .in(start_adc), .out(start));
lpm_adcnt		lpm_adcnt_inst (.clock(clk8), .cnt_en(cnten_adcnt), .sclr(sclr_adcnt), .aclr(~resetn), .q(ADCNT));
lpm_adccomp		lpm_adccomp_inst (.dataa(ADCNT), .datab(ADCNT_REF), .ageb(done_adcnt));
lpm_sftreg		lpm_sftreg_inst (.clock(DCLK), .shiftin(DIN), .sclr(sclr_sftreg), .aclr(~resetn), .q(VOUT));

always @(posedge clk8 or negedge resetn)
begin: NEXT_CURR
if (!resetn)
	STATE <= IDLE;
else
	case (STATE)
		IDLE:
			if (start) STATE <= INIT;
			else STATE <= IDLE;
		INIT: STATE <= CLKLOW;
		CLKLOW:
			if (done_adcnt) STATE <= IDLE;
			else STATE <= CLKHIGH;
		CLKHIGH: STATE <= CLKLOW;
	endcase
end

always @(STATE)
begin: STATE_DECODING
case (STATE)
	IDLE:
		begin
			CSn = 1;
			DCLK = 0;
			sclr_sftreg = 0;
			cnten_adcnt = 0;
			sclr_adcnt = 0;
			idle_adc = 1;
		end
	INIT:
		begin
			CSn = 1;
			DCLK = 0;
			sclr_sftreg = 1;
			cnten_adcnt = 0;
			sclr_adcnt = 1;
			idle_adc = 0;
		end
	CLKLOW:
		begin
			CSn = 0;
			DCLK = 0;
			sclr_sftreg = 0;
			cnten_adcnt = 0;
			sclr_adcnt = 0;
			idle_adc = 0;
		end
	CLKHIGH:
		begin
			CSn = 0;
			DCLK = 1;
			sclr_sftreg = 0;
			cnten_adcnt = 1;
			sclr_adcnt = 0;
			idle_adc = 0;
		end
endcase
end
endmodule
	